package com.dynamic.data.source.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.dynamic.data.source.config.datasource.DataSourceAdmin;
import com.dynamic.data.source.config.datasource.DataSourceInfo;
import com.dynamic.data.source.domain.User;
import com.dynamic.data.source.mapper.UserMapper;
import com.dynamic.data.source.service.InitService;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Properties;

/**
 * 开发公司：联信
 * 版权：联信
 * <p>
 * Annotation
 *
 * @author 刘志强
 * @created Create Time: 2021/1/26
 */
@Service
public class InitServiceImpl implements InitService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    @Qualifier("poolProperties")
    private Properties poolProperties;
    @Autowired
    private MybatisProperties mybatisProperties;
    @Autowired
    private ResourceLoader resourceLoader;

    @Override
    public void initDataSource() {
        List<User> list = userMapper.getUserAll();
        list.forEach(user -> {
            DataSourceInfo dataSourceInfo = new DataSourceInfo();
            dataSourceInfo.setUserId(user.getId());

            StringBuilder url = new StringBuilder();
            url.append("jdbc:mysql://").append(user.getDatabaseIp())
                    .append(":3306/")
                    .append(user.getDatabaseName())
                    .append("?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=round&useAffectedRows=true");

            // 创建数据源
            DruidDataSource dataSource = DataSourceBuilder.create()
                    // 数据库 连接池类型 如果不设置类型默认类型为 com.zaxxer.hikari.HikariDataSource
                    .type(DruidDataSource.class)
                    // 驱动
                    .driverClassName("com.mysql.cj.jdbc.Driver")
                    // 链接
                    .url(url.toString())
                    // 账号
                    .username(user.getDatabaseAccount())
                    // 密码
                    .password(user.getDatabasePassword())
                    .build();

            // 加载连接池配置信息
            dataSource.configFromPropety(poolProperties);
            dataSourceInfo.setDataSource(dataSource);

            // 创建SqlSessionFactoryBean
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            bean.setTypeAliasesPackage(mybatisProperties.getTypeAliasesPackage());
            bean.setConfigLocation(resourceLoader.getResource(mybatisProperties.getConfigLocation()));
            bean.setMapperLocations(mybatisProperties.resolveMapperLocations());
            try {
                dataSourceInfo.setSqlSessionFactory(bean.getObject());
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                dataSourceInfo.setSqlSessionFactory(bean.getObject());
            } catch (Exception e) {
                e.printStackTrace();
            }
            DataSourceAdmin.dataSourceMap.put(user.getId(),dataSourceInfo);
        });
    }
}
